"""
FileName：auth_manager.py
Description：
Author：gaojiahui
Time：2025/8/14 14:46
Website：https://gitee.com/gao-jiahui
"""
import base64

import requests

"""
Pig登录接口响应结构
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expires_in": 43199,
  "scope": "server"
}
"""
class AuthManager:
    def __init__(self,base_url):
        self.base_url = base_url
        self.token = None
        self.refresh_token = None
        self.session = requests.Session()

    def login(self,username,password):
        """执行登录并提取Token"""
        url = f"{self.base_url}/auth/oauth/token"

        # 客户端认证
        auth_header = {
            "Authorization": "Basic " + base64.b64encode(b"test:test").decode()
        }

        # 请求数据
        data = {
            "username":username,
            "password":password,
            "grant_type":"password",
            "scope":"server",
            "code":"8888",  # 简化处理
            "randomStr":"test_uuid"
        }

        response = self.session.post(url,data=data,headers=auth_header)

        if response.status_code == 200:
            token_data = response.json()
            self.token = token_data["access_token"]
            self.refresh_token = token_data["refresh_token"]
            return True

        print(f"登录失败:{response.text}")
        return False

    def get_auth_headers(self):
        """获取认证头"""
        if not self.token:
            raise ValueError("用户未登录")
        return {"Authorization": f"Bearer {self.token}"}